<?php

namespace App\Console\Commands\ThirdOrder;

use App\Console\Base;
use App\Services\ThirdAPI\GNSAPIService;
use App\Models\Game;
use App\Models\PartnerConfig;
use Bluerhinos\phpMQTT;
use common\enum\CommonEnum;

class FGBonusPoolProcesser extends Base
{
    //一次订阅获取两次消息后停止消息推送  60秒采集一次
    protected $signature = self::PREFIX . 'fgBonusPool';
    protected $description = 'FG奖池拉取';
    public $getTimes = 0;
    const PARTNER_NAME = 'FG';
    //线上配置MQTT配置
    public $prodSetting = [
        'server' => 'api.fungaming.me',
        'port' => 1883,
        'username' => 'fungaming',
        'password' => 'jh374SDYU',
        'client_id ' => "clientx9293670xxctrty",
        'topic' => 'fg'
    ];
    //测试环境配置
    public $testSetting = [
        'server' => 'api.ppro.98078.net',
        'port' => 1882,
        'username' => 'fungaming',
        'password' => 'jh374SDYU',
        'client_id ' => "clientx9293670xxctrt",
        'topic' => 'fg'
    ];

    public function message($topic, $msg)
    {
        $this->getTimes = $this->getTimes + 1;
        $this->info("===== 收到订阅消息数据" . json_encode($msg));
        $this->info("===== 收到订阅消息" . $topic);
        $result = json_decode($msg, true);
        if (isset($result['data']) && is_array($result['data'])) {
            $bonusPoolList = array_column($result['data'], 'jp');
            $sumBonus = array_sum($bonusPoolList);
            $updateModel = PartnerConfig::where(['partner_name'=>strtoupper(static::PARTNER_NAME),'game_type'=>CommonEnum::GAME_EGAME]);
            $updateData = [
                'jackpot'=>$sumBonus
            ];
            $updateModel->update($updateData);
            $this->info("===== 累计所有奖金池数据为" . $sumBonus);
        }


    }


    public function handle()
    {
        $this->info("===== FG获取奖金池环境为" . env('APP_ENV'));
        if (env('APP_ENV') == 'prod') {
            $setting = $this->prodSetting;
        } else {
            $setting = $this->testSetting;
        }
        // 订阅信息,接收一个信息后退出
        $server = $setting['server'];     // 服务代理地址(mqtt服务端地址)
        $port = $setting['port'];                     // 通信端口
        $username = $setting['username'];                   // 用户名(如果需要)
        $password = $setting['password'];                   // 密码(如果需要
        $client_id = "clientx9293670xxctrt"; // 设置你的连接客户端id
        $mqtt = new phpMQTT($server, $port, $client_id);
        $mqtt->connect(true, NULL, $username, $password);
        $topics[$setting['topic']] = array("qos" => 0, "function" => array($this, "message"));
        // 订阅主题为 SN69143809293670state qos为0
        $mqtt->subscribe($topics, 0);
        while ($mqtt->proc()) {
            //每次任务获取两次之后就停止订阅
            if ($this->getTimes > 1) {
                exit("已获取到FG奖金池数据");
            }
        }
        $mqtt->close();
        $mqtt->disconnect();
        $this->info("===== 采集FG奖金池完成");
    }


}
